import functools
from flask.scaffold import F
from flask_mobility.decorators import mobilized
from werkzeug.security import check_password_hash
from flask import Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app
from .router import to_route

from .crud import Users
from .database import db
from .schemas import auth_schema

bp = Blueprint('auth', __name__, url_prefix='/auth')


def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))
        return view(**kwargs)

    return wrapped_view


@bp.route('/login', methods=('GET', 'POST'))
def login():
    if request.method == 'POST':
        try:
            data = auth_schema.load(request.form.to_dict())
            user = Users.get_user_by_email(db.session, data['email'])
            if user is None:
                raise ValueError("Incorrect email.")

            if not check_password_hash(user.hashed_password, data['password']):
                raise ValueError("Incorrect password.")

            session.clear()
            session['user_id'] = user.id
            if user.role.name == 'admin':
                return redirect(url_for('manage.professor'))
            elif user.role.name == 'student':
                return redirect(url_for('student.course'))
            elif user.role.name == 'professor':
                return redirect(url_for('professor.professor'))
        except Exception as e:
            flash(str(e))
        school = current_app.config.get('SCHOOL_NAME')
        return to_route('auth/login.html', school=school)
    else:
        school = current_app.config.get('SCHOOL_NAME')
        return to_route('auth/login.html', school=school)
